<template>
  <div class="loginlog-container-padding">
    <vxe-grid
      ref="xGrid"
      border
      stripe
      keep-source
      auto-resize
      sync-resize
      :height="height"
      :loading="listLoading"
      :column-config="{ resizable: true }"
      :export-config="{}"
      :columns="tableColumn"
      align="center"
      :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
      :seq-config="{ seqMethod: seqMethod }"
    >
      <template #form>
        <vxe-form
          ref="queryform"
          title-align="right"
          title-width="130"
          prevent-submit
        >
          <vxe-form-item title="用户名称" span="8">
            <template #default>
              <el-input
                v-model="queryForm.username"
                placeholder="用户名称"
                style="width: 150px"
                clearable
              />
            </template>
          </vxe-form-item>
          <vxe-form-item title="登录地址" span="8">
            <template #default>
              <el-input
                v-model="queryForm.userIp"
                placeholder="登录地址"
                clearable
              />
            </template>
          </vxe-form-item>
          <vxe-form-item title="日期" span="8">
            <template #default>
              <el-date-picker
                v-model="queryForm.createTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 240px"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              />
            </template>
          </vxe-form-item>
          <vxe-form-item span="24" align="center">
            <el-button plain :icon="Search" @click="queryData">搜索</el-button>
            <el-button
              v-permissions="{ permission: ['system:login-log:export'] }"
              type="success"
              plain
              :loading="exportLoading"
              @click="handleExport"
            >
              <i class="iconfont-fw ri-download-2-line" />
              导出
            </el-button>
          </vxe-form-item>
        </vxe-form>
      </template>
      <template #logType="{ row }">
        <el-tag type="primary">{{ logType(row) }}</el-tag>
      </template>
      <template #logRet="{ row }">
        <el-tag :type="row.result === 0 ? 'primary' : 'danger'">
          {{ logRet(row) }}
        </el-tag>
      </template>
      <template #openRet="{ row }">
        <el-link @click="handleEdit(row)">{{ row.username }}</el-link>
      </template>
      <template #bottom>
        <el-pagination
          background
          :current-page="queryForm.pageNo"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </template>
    </vxe-grid>
    <loginlogEdit ref="loginlogEdit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { exportLoginLog, getLoginLogPage } from '@/api/system/loginLog'
  import { getDictType } from '@/api/system/dict/dict.data'
  import download from '@/utils/download'
  import { Search } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'Loginlog',
    components: {
      loginlogEdit: defineAsyncComponent(() =>
        import('./components/loginlogEdit')
      ),
    },
    setup() {
      const $baseTableHeight = inject('$baseTableHeight')

      const state = reactive({
        height: $baseTableHeight(0),
        xGrid: 'xGrid',
        loginlogEdit: null,
        exportLoading: false,
        tableColumn: [
          { type: 'seq', title: '序号', width: 50 },
          {
            title: '操作类型',
            field: 'log',
            width: 80,
            slots: { default: 'logType' },
          },
          {
            title: '用户名称',
            field: 'username',
            width: 160,
            slots: { default: 'openRet' },
          },
          {
            title: '登录地址',
            field: 'userIp',
            width: 230,
          },
          {
            title: '浏览器',
            field: 'userAgent',
            width: 320,
          },
          {
            title: '登陆结果',
            field: 'result',
            width: 120,
            slots: { default: 'logRet' },
          },
          {
            title: '登录日期',
            width: 160,
            field: 'createTime',
            formatter: ['formatDate', 'yyyy-MM-dd HH:mm:ss'],
          },
        ],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        queryForm: {
          pageNo: 1,
          pageSize: 30,
          username: undefined,
          userIp: '',
          createTime: [],
        },
        system_login_type: [],
        system_login_result: [],
      })

      const fetchData = () => {
        state.listLoading = true
        console.log(state.queryForm)
        getLoginLogPage(state.queryForm)
          .then((res) => {
            if (res.code == 0 || res.code == 200) {
              state['xGrid'].reloadData(res.data.list)
              state.total = res.data.total
              state.listLoading = false
            } else {
              state.listLoading = false
            }
          })
          .catch((err) => {
            state.listLoading = false
          })
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNo = 1
        fetchData()
      }
      const seqMethod = ({ row, rowIndex, column, columnIndex }) => {
        return (
          (state.queryForm.pageNo - 1) * state.queryForm.pageSize + rowIndex + 1
        )
      }

      const dictType = () => {
        getDictType({ dictType: 'system_login_type' })
          .then((res) => {
            state.system_login_type = res.data
          })
          .catch((err) => {
            state.listLoading = false
          })
      }

      const logRetType = () => {
        getDictType({ dictType: 'system_login_result' })
          .then((res) => {
            state.system_login_result = res.data
          })
          .catch((err) => {
            state.listLoading = false
          })
      }

      const handleExport = async () => {
        state.exportLoading = true
        const data = await exportLoginLog(state.queryForm)
        download.excel(data, '登录日志.xls')
        state.exportLoading = false
      }

      onMounted(() => {
        dictType()
        logRetType()
        fetchData()
      })

      const logType = (val) => {
        let type = ''
        state.system_login_type.forEach((item) => {
          if (`${val.logType}` === item.value) {
            type = item.label
          }
        })
        return type
      }

      const logRet = (val) => {
        let type = ''
        state.system_login_result.forEach((item) => {
          if (`${val.result}` === item.value) {
            type = item.label
          }
        })
        return type
      }

      onBeforeMount(() => {
        window.addEventListener('resize', handleHeight)
      })

      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleHeight)
      })

      const handleHeight = () => {
        state.height = $baseTableHeight(0)
      }

      const handleEdit = (row) => {
        state['loginlogEdit'].showEdit(row)
      }

      return {
        ...toRefs(state),
        fetchData,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        Search,
        seqMethod,
        logType,
        logRet,
        handleExport,
        handleEdit,
      }
    },
  })
</script>
